package com.laivi.basic.module.monitor;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.Executors;

import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyException;
import net.contentobjects.jnotify.JNotifyListener;

import com.laivi.basic.common.constants.Constant;
import com.laivi.basic.common.listener.CallBack;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-14
 * description:
 */
public class FileMonitor {
	private static boolean isRun=true;

	public static void monitor(final String dir,final CallBack back){
		Executors.newCachedThreadPool().submit(new Runnable() {

			@Override
			public void run() {
				try {
					WatchService watch=FileSystems.getDefault().newWatchService();
					Path path = Paths.get(dir);
					path.register(watch, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
					while(true){
						WatchKey key=watch.take();
						for(WatchEvent<?> event:key.pollEvents()){
							File file=new File(dir+"\\"+event.context());
							if(file.isDirectory()&& "ENTRY_CREATE".equals(String.valueOf(event.kind()))){
								path.resolve(String.valueOf(event.context()));
							}
							back.execute(event.context(),event.kind());
						}
						if(!key.reset()){
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void monitor(final String dir,final JNotifyListener monitor){
		Executors.newCachedThreadPool().submit(new Runnable() {

			@Override
			public void run() {
				int mask=JNotify.FILE_CREATED|JNotify.FILE_DELETED|JNotify.FILE_MODIFIED|JNotify.FILE_RENAMED;
				int watchId=0;
				try {
					watchId=JNotify.addWatch(dir, mask, true, monitor);
					while(isRun){
						Thread.sleep(10*Constant.Time.MIN);
					}
					//JNotify.removeWatch(watchId);
				} catch (JNotifyException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally{
					try {
						JNotify.removeWatch(watchId);
					} catch (JNotifyException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
}
